//
//  BKCollectionViewLayout.m
//  XPhoto
//
//  Created by baboy on 2019/8/15.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "BKCollectionViewLayout.h"
@interface BKCollectionViewLayout()
@property(nonatomic, strong) NSMutableArray *sectionHeights;
@property(nonatomic, strong) NSMutableArray *sectionColumnHeights; //section 每一列的frame
@end

@implementation BKCollectionViewLayout

- (CGFloat)offsetHeightOfSection:(NSInteger)section{
    NSInteger i = section - 1;
    if (!self.sectionColumnHeights || i <0 || i >= self.sectionColumnHeights.count) {
        return 0;
    }
    NSArray *columnHeights = [self.sectionColumnHeights objectAtIndex:i];
    CGFloat maxHeight = 0;
    for (NSInteger i = 0, n = [columnHeights count]; i < n; i++) {
        CGFloat h = [[columnHeights objectAtIndex:i] floatValue];
        maxHeight = MAX(maxHeight, h);
    }
    return maxHeight;
}
- (NSInteger)numberOfColumnsInSection:(NSInteger)section{
    NSInteger numberOfColumns = self.numberOfColumns;
    if (self.delegate && [self.delegate respondsToSelector:@selector(collectionViewLayout:numberOfColumnsInSection:)]) {
        numberOfColumns = [self.delegate collectionViewLayout:self numberOfColumnsInSection:section];
    }
    return numberOfColumns;
}
- (CGFloat)itemWidthInSection:(NSInteger)section{
    NSInteger numberOfColumns = [self numberOfColumnsInSection:section];
    CGFloat itemWidth = self.collectionView.bounds.size.width/numberOfColumns;
    return itemWidth;
}
- (CGFloat)itemHeightInSection:(NSInteger)section{
    CGFloat itemHeight = [self.delegate collectionViewLayout:self heightForItemInSection:section];
    return itemHeight;
}
- (NSInteger)minHeightColumnInSection:(NSInteger)section{
    NSInteger column = 0;
    NSArray *columnHeights = [self.sectionColumnHeights objectAtIndex:section];
    
    for (NSInteger i = 1, n = columnHeights.count; i < n; i++) {
        CGFloat h = [[columnHeights objectAtIndex:i] floatValue];
        CGFloat h2 = [[columnHeights objectAtIndex:column] floatValue];
        if (h < h2) {
            column = i;
        }
    }
    return column;
}
- (void)prepareLayout{
    [super prepareLayout];
    
    self.itemAttributes = [NSMutableArray array];
    self.sectionHeights = [NSMutableArray array];
    self.sectionColumnHeights = [NSMutableArray array];
    
    NSInteger numSections = [self.collectionView numberOfSections];
    CGFloat sectionOffsetY = 0;
    
    for(NSInteger section = 0; section < numSections; section++){
        
        //header 高度
        CGFloat headerHeight = 0;
        if (self.delegate && [self.delegate respondsToSelector:@selector(collectionViewLayout:heightForHeaderInSection:)]) {
            headerHeight = [self.delegate collectionViewLayout:self heightForItemInSection:section];
        }
        sectionOffsetY += headerHeight;
        
        NSInteger numberOfColumns = [self numberOfColumnsInSection:section];
        NSMutableArray *columnHeights = [NSMutableArray array];
        for(NSInteger i = 0; i < numberOfColumns; i++){
            [columnHeights addObject:[NSNumber numberWithFloat:sectionOffsetY]];
        }
        [self.sectionColumnHeights addObject:columnHeights];
        
        CGFloat itemWidth = [self itemWidthInSection:section];
        CGFloat itemHeight = [self itemHeightInSection:section];
        
        
        NSInteger numOfItems = [self.collectionView numberOfItemsInSection:0];
        for(NSInteger i = 0; i < numOfItems; i++){
            NSInteger nColumn = [self minHeightColumnInSection:section];
            CGFloat y = [[columnHeights objectAtIndex:nColumn] floatValue];
            
            
            NSInteger hSpan = 1;
            NSInteger vSpan = 1;
            if (self.layoutMode == BKCollectionViewLayoutModeColumnAndRowSpan) {
                if (i%5 == 0 && nColumn < (numberOfColumns - 1) ) {
                    CGFloat y2 = [[columnHeights objectAtIndex:(nColumn+1)] floatValue];
                    if (y2 == y) {
                        hSpan = 2;
                        vSpan = 2;
                    }
                }
            }
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:section];
            CGRect itemFrame = CGRectMake(nColumn * itemWidth, y, itemWidth * hSpan, itemHeight * vSpan);
            CGRect contentFrame = itemFrame;
            contentFrame.size.height -= 1;
            if (nColumn > 0) {
                contentFrame.origin.x += 1;
                contentFrame.size.width -= 1;
            }
            UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
            attributes.frame = contentFrame;
            sectionOffsetY = MAX(sectionOffsetY, itemFrame.origin.y + itemFrame.size.height);
            [self.itemAttributes addObject:attributes];
            
            CGFloat columnHeight = itemFrame.origin.y + itemFrame.size.height;
            [columnHeights replaceObjectAtIndex:nColumn withObject:[NSNumber numberWithFloat: columnHeight]];
            
            if (hSpan > 1) {
                [columnHeights replaceObjectAtIndex:(nColumn+1) withObject:[NSNumber numberWithFloat: columnHeight]];
            }
        }
        if (self.delegate && [self.delegate respondsToSelector:@selector(collectionViewLayout:heightForFooterInSection:)]) {
            CGFloat footerHeight = [self.delegate collectionViewLayout:self heightForFooterInSection:section];
            sectionOffsetY += footerHeight;
        }
        [self.sectionHeights addObject:[NSNumber numberWithFloat:sectionOffsetY]];
    }
}
/**
 *  2、
 *  需要返回所有内容的滚动长度
 */
- (CGSize)collectionViewContentSize{
    NSArray *columnHeights = [self.sectionColumnHeights lastObject];
    CGFloat maxHeight = 0;
    for (NSInteger i = 0, n = [columnHeights count]; i < n; i++) {
        CGFloat h = [[columnHeights objectAtIndex:i] floatValue];
        maxHeight = MAX(maxHeight, h);
    }
    CGSize contentSize = CGSizeMake(self.collectionView.bounds.size.width,maxHeight);
    return contentSize;
}
- (NSArray<UICollectionViewLayoutAttributes *> *) layoutAttributesForElementsInRect:(CGRect) rect{
    
    NSMutableArray *visibleAttributes = [NSMutableArray arrayWithArray:self.itemAttributes];
    if (self.delegate && [self.delegate respondsToSelector:@selector( collectionViewLayout:heightForHeaderInSection:)]) {        
        UICollectionViewLayoutAttributes *headerAttributes = [self layoutAttributesForSupplementaryViewOfKind:SUPPLEMENTARY_KIND_HEADER_VIEW atIndexPath:[NSIndexPath indexPathForItem:0 inSection:1]];
        [visibleAttributes addObject:headerAttributes];
    }
    return visibleAttributes;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    //return [super shouldInvalidateLayoutForBoundsChange:newBounds];
    return YES;
}

/**
 *  根据kind、indexPath，计算对应的LayoutAttributes
 */
- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:elementKind withIndexPath:indexPath];
    
    //计算LayoutAttributes
    if([elementKind isEqualToString:SUPPLEMENTARY_KIND_HEADER_VIEW]){
        CGFloat width = self.collectionView.bounds.size.width;
        CGFloat height = [self.delegate collectionViewLayout:self heightForHeaderInSection:indexPath.section];
        CGFloat headerFixedHeight = height;
        if (self.delegate && [self.delegate respondsToSelector:@selector(collectionViewLayout:floatHeightForHeaderInSection:)]) {
            headerFixedHeight = [self.delegate collectionViewLayout:self floatHeightForHeaderInSection:indexPath.section];
        }
        CGFloat x = 0;
        //根据offset计算kSupplementaryViewKindHeader的y
        //y = offset.y-(header高度-固定高度)
        CGFloat offsetY = MAX(self.collectionView.contentOffset.y, [self offsetHeightOfSection:indexPath.section]);
        
        
        CGFloat y = MAX(0, offsetY-(height-headerFixedHeight));
        attributes.frame = CGRectMake(x, y, width, height);
        attributes.zIndex = INT_MAX;
    }
    return attributes;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    //外部返回Item高度
    CGFloat itemHeight = [self.delegate collectionViewLayout:self heightForItemInSection:indexPath.section];
    CGFloat itemWidth = self.collectionView.bounds.size.width;
    //headerView高度
    CGFloat headerHeight = 0;
    if (self.delegate && [self.delegate respondsToSelector:@selector(collectionViewLayout:heightForHeaderInSection:)]) {
        headerHeight = [self.delegate collectionViewLayout:self heightForHeaderInSection:indexPath.section];
    }
    
    CGFloat x = 0;
    CGFloat y = [self offsetHeightOfSection:indexPath.section] + headerHeight;
    
    if (self.layoutMode == BKCollectionViewLayoutModeFixedWidthHeight &&
        [self.delegate respondsToSelector:@selector(collectionViewLayout:numberOfColumnsInSection:)]) {
        NSInteger numOfColumns = self.numberOfColumns;
        if (self.delegate && [self.delegate respondsToSelector:@selector(collectionViewLayout:numberOfColumnsInSection:)]) {
            numOfColumns =
            [self.delegate collectionViewLayout:self numberOfColumnsInSection:indexPath.section];
        }
        itemWidth = itemWidth/numOfColumns;
        x = (indexPath.row % numOfColumns) * itemWidth;
        y += ( (int)(indexPath.row/numOfColumns) ) * itemHeight;
        attributes.frame = CGRectMake(x, y, itemWidth, itemHeight);
    }
    return attributes;
}
@end
